package com.example.networkrequest;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.util.StateSet;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    EditText et_network_result, et_network_url, et_city;
    ImageView sector, pic;
    List idlist = new ArrayList<>();
    List namelist = new ArrayList();
    private ProgressDialog dialog;
    //ProgressDialog dialog = ProgressDialog.show(this, null, "正在请求中");
    private static String image_path = "http://10.0.0.204:8090/face/getWorkerHeadFace/a0ed10c4e74b4d2aa8797a0c5a4c9d57";
    private static String image_path1 = "http://api.btstu.cn/sjbz/api.php?lx=dongman&format=images";

    private static final String TAG = MainActivity.class.getSimpleName();
    private boolean isChecked = false;

    @SuppressLint("WrongViewCast")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et_network_result = findViewById(R.id.et_network_result);
        et_network_url = findViewById(R.id.et_network_url);
        pic = findViewById(R.id.imageView);
        et_city = findViewById(R.id.et_city);

        dialog = new ProgressDialog(this);
        dialog.setTitle("提示消息");
        dialog.setMessage("正在下载");
        dialog.setCancelable(false);


    }

    public void img_selector(View view) {
        isChecked = !isChecked;
        if (isChecked) {
            et_network_url.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            et_network_url.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
        sector.setSelected(isChecked);
    }

    public void urlConnectionGet(View view) {

        final ProgressDialog dialog = ProgressDialog.show(this, null, "正在请求中");
        new Thread() {
            @Override
            public void run() {
                //String urlpath = et_network_url.getText().toString();
                String urlpath ="http://10.0.0.204:8090/face/getWorkerHeadFace/a0ed10c4e74b4d2aa8797a0c5a4c9d57";
                try {
                    URL url = new URL(urlpath);
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("GET");
                    httpURLConnection.setConnectTimeout(100000);
                    httpURLConnection.setReadTimeout(200000);
                    httpURLConnection.connect();

                    InputStream is=httpURLConnection.getInputStream();
                    final Bitmap bitmap=BitmapFactory.decodeStream(is);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            pic.setImageBitmap(bitmap);
                        }
                    });
                    /*int responseCode = httpURLConnection.getResponseCode();
                    if (responseCode == 200) {
                        InputStream is = httpURLConnection.getInputStream();
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = is.read(buffer)) != -1) {
                            baos.write(buffer, 0, len);
                        }
                        final String result = baos.toString();
                        is.close();
                        baos.close();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                et_network_result.setText(result);
                                dialog.dismiss();
                            }
                        });
                    }*/
                    httpURLConnection.disconnect();

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }.start();
    }

    public void urlConnectionPost(View view) {
        final ProgressDialog dialog = ProgressDialog.show(this, null, "正在请求中");
        new Thread() {
            @Override
            public void run() {
                String urlpath = et_network_url.getText().toString();
                try {
                    URL url = new URL(urlpath);
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setConnectTimeout(6000);
                    httpURLConnection.setReadTimeout(6000);
                    httpURLConnection.connect();
                    int response = httpURLConnection.getResponseCode();
                    if (response == 200) {
                        InputStream is = httpURLConnection.getInputStream();
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = is.read(buffer)) != -1) {
                            baos.write(buffer, 0, len);
                        }
                        final String results = baos.toString();
                        is.close();
                        baos.close();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                et_network_result.setText(results);
                                dialog.dismiss();
                            }
                        });
                    }
                    httpURLConnection.disconnect();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

    public void OkHttpClientGet(View view) {
        final ProgressDialog dialog = ProgressDialog.show(this, null, "正在请求中");
        String urlpath = et_network_url.getText().toString();
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder().url(urlpath).get().build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "request失败");
            }

            @Override
            public void onResponse(Call call, Response response) {
                final String result = response.body().toString();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        et_network_result.setText(result);
                        dialog.dismiss();
                    }
                });
            }
        });
    }

    public void OkHttpClientPost(View view) {
        final ProgressDialog dialog = ProgressDialog.show(this, null, "正在请求中");
        String urlpath = et_network_url.getText().toString();
        RequestBody requestBody = new FormBody.Builder().add("name", "lucifer").add("age", "100").build();
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().post(requestBody).url(urlpath).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "onFailure");
            }

            @Override
            public void onResponse(Call call, Response response) {
                final String res = response.body().toString();
                Log.d("lucifer", response.protocol() + " " + response.code() + " " + response.message());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        et_network_result.setText(res);
                        dialog.dismiss();
                    }
                });
            }
        });

    }

    public void volleyGet(View view) {

    }

    public void volleyPost(View view) {

    }

    public void btn_addpic(View view) {
        new Thread(new loadpic()).start();
        dialog.show();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            Bitmap bitmap = (Bitmap) msg.obj;
            pic.setImageBitmap(bitmap);
            dialog.dismiss();
        }
    };

    public class loadpic implements Runnable {

        @Override
        public void run() {
            OkHttpClient okHttpClient = new OkHttpClient();
            Request request = new Request.Builder().url(image_path).get().build();
            okHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Toast.makeText(MainActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    InputStream is = response.body().byteStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(is);
                    Message msg = Message.obtain();
                    msg.obj = bitmap;
                    handler.sendMessage(msg);
                }
            });
        }
    }


    public static class okhttp {
        public static void sendrequestokhttp(String url, Callback callback) {
            OkHttpClient okHttpClient = new OkHttpClient();
            Request request = new Request.Builder().url(url).get().build();
            okHttpClient.newCall(request).enqueue(callback);
        }
    }

    public void btn_getcity(View view) throws MalformedURLException {
        okhttp.sendrequestokhttp("http://guolin.tech/api/china", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(MainActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                parseresponse(response);
            }
        });
    }

    //处理response
    private void parseresponse(Response response) throws IOException {
        //线程池是来实现
        /*ExecutorService executorService=Executors.newSingleThreadExecutor();
        executorService.submit(new Runnable() {
            @Override
            public void run() {

            }
        });*/
        final String responsedata = response.body().string();

        try {
            /*JSONArray jsonArray=new JSONArray(responsedata);
            for(int i=0;i<jsonArray.length();i++){
                JSONObject jsonObject=jsonArray.getJSONObject(i);
                final String id=jsonObject.getString("id");
                final String name=jsonObject.getString("name");
                idlist.add(id);
                namelist.add(name);

            }
*/
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    et_city.setText(responsedata);
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
